import { ActionTree, Module, MutationTree } from 'vuex'
import { IRootState } from '@/store'
import { RouteRecordRaw, RouteRecordNormalized } from 'vue-router'

// 为对象动态分配属性： 1、使用索引签名 2、 使用工具类型Record定义接口 https://zhuanlan.zhihu.com/p/398170136
interface LooseObject { // 索引签名
  [key: string]: string
}
export interface RouteLocationWithFullPath extends RouteRecordNormalized {
  fullPath?: string;
  query?: LooseObject
}
export interface ITagsViewState {
  visitedViews: RouteLocationWithFullPath[];
}

const mutations: MutationTree<ITagsViewState> = {
  // 添加可显示tags view
  ADD_VISITED_VIEW(state, view) {
    // 过滤去重
    if (state.visitedViews.some(v => v.path === view.path)) return
    state.visitedViews.push(Object.assign({}, view, {
      title: view.meta.title || 'tag-name'
    }))
    console.log('state.visitedViews', state.visitedViews)
  },
  DEL_VISITED_VIEW(state, view) {
    const i = state.visitedViews.indexOf(view)
    if (i > -1) {
      state.visitedViews.splice(i, 1)
    }
  }
}

const actions: ActionTree<ITagsViewState, IRootState> = {
  // 添加tags view
  addView({ dispatch }, view: RouteRecordRaw) {
    dispatch('addVisitedView', view) // ? 为什么要再包一层
  },
  // 添加可显示的tags view 添加前commit里需要进行去重过滤
  addVisitedView({ commit }, view: RouteRecordRaw) {
    console.log('addVisitedView', view)
    commit('ADD_VISITED_VIEW', view)
  },
  // 删除tags view
  delView({ dispatch }, view: RouteRecordRaw) {
    return new Promise(resolve => {
      dispatch('delVisitedView', view) // ? 为什么要再包一层 为了解耦,可以在这里做其他判断
      resolve(null)
    })
  },
  // 从可显示的集合中 删除tags view
  delVisitedView({ commit }, view: RouteRecordRaw) {
    commit('DEL_VISITED_VIEW', view)
  }
}

const tagsView: Module<ITagsViewState, IRootState> = {
  namespaced: true,
  state: {
    visitedViews: []
  },
  mutations,
  actions
}

export default tagsView
